import usePage from "@/hooks/usePage";
import { ElMessageBox, ElMessage } from "element-plus";
export default function (api, options) {
  const {
    formatResult,
    onSuccess,
    immediate,
    rowKey,
    resultKey = "rows",
    getCountStatistics,
  } = options || {};
  const { pagination, currentChange, sizeChange } = usePage(() => {
    getTableData();
  });
  const loading = ref(false);
  const tableData = ref([]);
  //获取数据
  const getTableData = async () => {
    try {
      loading.value = true;
      const res = await api({
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize,
      });
      let list = [];
      list = res[resultKey];
      pagination.total = res.total;
      tableData.value = formatResult ? formatResult(list) : list;
      onSuccess && onSuccess();
    } finally {
      loading.value = false;
    }
  };
  // 是否立即触发
  const isImmediate = immediate ?? true;
  isImmediate && getTableData();
  // 检索
  const search = () => {
    currentChange(1);
  };
  //删除操作
  const handleDelete = async (delApi, params) => {
    ElMessageBox.confirm("是否确认删除？", "提示", {
      type: "warning",
    }).then(async () => {
      try {
        console.log(params)
        const res = await delApi(params);
        if (res.code == 200) {
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
          getTableData();
          //获取数量统计
          getCountStatistics && getCountStatistics();
        }
      } catch (error) {
        console.log(error);
      }
    });
  };
  return {
    loading,
    pagination,
    sizeChange,
    currentChange,
    tableData,
    search,
    handleDelete,
  };
}
